﻿using MediatR;
using Micro.Extensions.DDD.Bus;
using Micro.Extensions.DDD.Commands;
using Micro.Extensions.SqlSugar.UnitOfWork;
using Micro.Utils;
using Module.Test.Domain.Commands.Customs;
using Module.Test.Domain.Events.Customs;
using Module.Test.Domain.IRepositorys;
using Module.Test.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Module.Test.Domain.CommandHandlers
{
    public class CustomCommandHandler : CommandHandler
        , IRequestHandler<RegisterCustomCommand, bool>
        , IRequestHandler<RemoveCustomCommand, bool>
        , IRequestHandler<UpdateCustomCommand, bool>
    {
        /// <summary>
        /// 工作单位
        /// </summary>
        private readonly IUnitOfWork _uow;

        private readonly ICustomRepository _customRepository;

        public CustomCommandHandler(IMediatorHandler bus, IUnitOfWork uow, ICustomRepository customRepository) : base(bus)
        {
            this._uow = uow;
            this._customRepository = customRepository;
        }

        /// <summary>
        /// RegisterCustomCommand命令的处理程序
        /// 整个命令处理程序的核心都在这里
        /// 不仅包括命令验证的收集，持久化，还有领域事件和通知的添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(RegisterCustomCommand request, CancellationToken cancellationToken)
        {
            // 命令验证
            if (!request.IsValid())
            {
                // 错误信息收集
                NotifyValidationErrors(request);
                return await Task.FromResult(false);
            }

            // 判断名称是否存在
            // 这些业务逻辑，当然要在领域层中（领域命令处理程序中）进行处理
            if (await _customRepository.ExistName(request.Name))
            {
                AddError("名称已存在！");
                return await Task.FromResult(false);
            }

            // 实例化领域模型，这里才真正的用到了领域模型
            // 注意这里是通过构造函数方法实现
            var custom = new Custom(SnowflakeId.Default().NextId(), request.Name, request.CreatedTime);

            //持久化
            var result = await _customRepository.Add(custom);
            if (result > 0)
            {
                // 提交成功后，这里需要发布领域事件
                // 比如欢迎用户注册邮件呀，短信呀等
                await _bus.PublishEvent(new RegisteredCustomEvent(custom.Id, custom.Name, custom.CreatedTime));
            }
            else
            {
                AddError("添加失败！");
                return await Task.FromResult(false);
            }

            return await Task.FromResult(true);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(RemoveCustomCommand request, CancellationToken cancellationToken)
        {
            // 命令验证
            if (!request.IsValid())
            {
                // 错误信息收集
                NotifyValidationErrors(request);
                return await Task.FromResult(false);
            }

            var custom = await _customRepository.QueryById(request.Id);
            if (custom == null!)
            {
                AddError("记录不存在！");
                return await Task.FromResult(false);
            }

            //持久化
            var result = await _customRepository.Delete(custom);
            if (result)
            {
                //发布领域事件
                await _bus.PublishEvent(new RemovedCustomEvent(custom.Id));
            }
            else
            {
                AddError("修改失败！");
                return await Task.FromResult(false);
            }

            return await Task.FromResult(true);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<bool> Handle(UpdateCustomCommand request, CancellationToken cancellationToken)
        {
            // 命令验证
            if (!request.IsValid())
            {
                // 错误信息收集
                NotifyValidationErrors(request);
                return await Task.FromResult(false);
            }
            // 判断名称是否存在
            // 这些业务逻辑，当然要在领域层中（领域命令处理程序中）进行处理
            if (await _customRepository.ExistName(request.Id, request.Name))
            {
                AddError("名称已存在！");
                return await Task.FromResult(false);
            }

            var custom = await _customRepository.QueryById(request.Id);
            if (custom == null!)
            {
                AddError("记录不存在！");
                return await Task.FromResult(false);
            }

            //持久化
            var result = await _customRepository.Update(custom);
            if (result)
            {
                //发布领域事件
                await _bus.PublishEvent(new UpdatedCustomEvent(custom.Id, custom.Name, custom.CreatedTime));
            }
            else
            {
                AddError("修改失败！");
                return await Task.FromResult(false);
            }

            return await Task.FromResult(true);
        }
    }
}
